package com.dy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.mapper.DyUserMapper;
import com.dy.mapper.DyUserRolesMapper;
import com.dy.pojo.dto.DyUserDTO;
import com.dy.pojo.dto.DyUserRestDTO;
import com.dy.pojo.entity.DyUserEntity;
import com.dy.pojo.entity.DyUserRolesEntity;
import com.dy.service.DyUserService;
import com.dy.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @ClassName:
 * @Author: 仄言in
 * @Desctiption: (描述)
 * @Date: 2021/6/1 17:27
 * @Version 1.0 (版本)
 */
@Service
public class DyUserServiceImpl extends ServiceImpl<DyUserMapper, DyUserEntity> implements DyUserService {
    @Autowired
    private DyUserMapper dyUserMapper;
    @Autowired
    private DyUserRolesMapper dyUserRolesMapper;

    @Override
    public void loginUser(DyUserDTO dyUserDTO) {
        UsernamePasswordToken token = new UsernamePasswordToken(dyUserDTO.getUsername(), dyUserDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
    }

    @Override
    public boolean restUser(DyUserRestDTO dyUserRestDTO) {
        DyUserEntity entity = dyUserMapper.selectOne(new QueryWrapper<DyUserEntity>().eq("username", dyUserRestDTO.getUsername()));
        if (entity != null) {
            return false;
        }
        DyUserEntity dyUserEntity = new DyUserEntity();
        String code="U"+System.currentTimeMillis();
        dyUserEntity.setCode(code)
                .setNickname(dyUserRestDTO.getNickname())
                .setUsername(dyUserRestDTO.getUsername())
                .setSalt(Md5Util.getSalt())
                .setPassword(Md5Util.encryptPassword(dyUserRestDTO.getPassword(),dyUserEntity.getSalt()))
                .setEmail(dyUserRestDTO.getEmail())
                .setAvatar(dyUserRestDTO.getAvatar());
        dyUserMapper.insert(dyUserEntity);
        //让所有新注册的用户都是普通用户
        DyUserRolesEntity rolesEntity = new DyUserRolesEntity();
        rolesEntity.setUserCode(code)
                .setRolesCode("R10002");
        dyUserRolesMapper.insert(rolesEntity);
        return true;
    }

    @Override
    public String listcode(String username) {
        DyUserEntity dyUserEntity = dyUserMapper.selectOne(new QueryWrapper<DyUserEntity>().select("code").eq("username", username));
        return dyUserEntity.getCode();
    }
}
